package com.bhh.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author bhh
 * @description 测试Socket, 配合SocketClientTest类使用
 * 该类是服务端
 * @date Created in 2021-04-06 20:03
 * @modified By
 */
@Slf4j
public class SocketServerTest {
    public static void main(String[] args) {

        final int PORT = 8888;
        BufferedWriter writer = null;
        final String QUIT = "quit";
        ServerSocket serverSocket = null;

        // 使用try-with-resource方式创建ServerSocket, 确保使用完后, ServerSocket会被关闭
        // 绑定监听端口
        try {
            serverSocket = new ServerSocket(PORT);
            log.info("服务器已启动, 监听端口" + PORT);
            // 循环工作
            while (true) {
                // 获取到了连接到ServerSocket的socket
                Socket socket = serverSocket.accept();
                log.info("客户端[" + socket.getPort() + "]已连接");

                // 创建IO流
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream())
                );
                writer = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                );

                String str = null;
                while (!QUIT.equals(str)) {
                    // 获取socket发送的数据
                    str = reader.readLine();
                    if (str == null) {
                        throw new RuntimeException("客户端发生错误");
                    }
                    if (QUIT.equals(str)) {
                        log.info("客户端[" + socket.getPort() + "] 断开连接");
                    } else {
                        log.info("客户端[" + socket.getPort() + "] : " + str);
                    }

                    // 返回信息到socket
                    writer.write("服务器 : " + str + "\n");
                    writer.flush();
                }
            }
        } catch (Exception e) {

        } finally {
//            try {
//                serverSocket.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(serverSocket);
        }
    }
}
